package org.example.router.impl;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.example.client.ServiceBClient;
import org.example.common.R;
import org.example.interceptor.MyHttpServletRequestWrapper;
import org.example.po.Routerparameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * @version 1.0
 * @description TODO
 * @date 2024/10/14 21:49
 */
@Component("DefaultRouterImpl")
public class DefaultRouterImpl extends RouterAbstract{
    public static final Logger LOGGER = LoggerFactory.getLogger(DefaultRouterImpl.class);

    @Override
    public boolean execute(Map<String, String> map, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException {
        String tradeCode = map.get("rulename");
        String projectName = map.get("projectName");
        List<Routerparameters> list = searchDatabase(tradeCode + "_" + projectName);
        if(list == null){
            // 为true则不拦截 不路由
            return true;
        }
        // 所有字段都匹配才进行路由
        for (Routerparameters routerparameter : list) {
            String ruleField = routerparameter.getRuleid();
            String ruleValue = routerparameter.getRulevalue();
            String value = map.get(ruleField);
            if (!(StringUtils.isNotBlank(value) && value.equals(ruleValue))) {
                return true;
            }
        }
        LOGGER.info("准备转发");

        R result = R.error();
        result.setMessage("未配置对应的处理逻辑");

        String methodName = map.get("method");
        Method method = ReflectUtil.getMethodByName(ServiceBClient.class, methodName);
        result = (R) method.invoke(serviceBClient, map);
        String s = JSON.toJSONString(result);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(s);
        return false;
    }
}
